//
//  TTLiveChatViewController.swift
//  TTProduct
//
//  Created by Toj on 3/26/21.
//  Copyright © 2021 TTProduct. All rights reserved.
//

import Cocoa

class TTLiveChatViewController: VNViewController {
    
    private var allMessage: [TTChatMessage]?
    private var teacherMessages: [TTChatMessage]?
    private var messages: [TTChatMessage]? {
        didSet {
            chatsTableView.reloadData()
            let count = messages?.count ?? 1
            chatsTableView.scrollRowToVisible(count-1)
        }
    }
    
    private lazy var inputView: NSView = {
        let view = NSView()
        view.tt_cornerRadius(9)
        view.tt_border(color: NSColor.init(hexColor: "#E9EEF2"))
        view.tt_backgroundColor = NSColor.init(hexColor: "#E9EEF2")
        return view
    }()
    
    private lazy var handButton: TTButton = {
        let view = TTButton()
        view.tt_setImage(NSImage(named: "liveChatHand"), for: .normal)
        view.tt_backgroundColor = .white
        return view
    }()
    
    private lazy var separatorView: NSView = {
        let view = NSView()
        view.tt_backgroundColor = NSColor.init(hexColor: "#E9EEF2")
        return view
    }()
    
    private lazy var emojiView: TTEmoticonView = {
        let view = TTEmoticonView()
        view.delegate = self
        view.tt_backgroundColor = .white
        return view
    }()
    
    private lazy var textScrollView: NSScrollView = {
        let view = NSScrollView()
        view.scrollerStyle = .overlay
        view.scrollerKnobStyle = .dark
        view.autohidesScrollers = true
        view.verticalScrollElasticity = .automatic
        view.documentView = textView
        view.backgroundColor = NSColor.init(hexColor: "#E9EEF2")
        view.drawsBackground = true
        return view
    }()
    
    private lazy var textView: NSTextField = {
        let view = NSTextField()
        view.delegate = self
        view.isBezeled = false
        view.focusRingType = .none
        view.placeholderString = "请输入消息"
        view.font = NSFont.systemFont(ofSize: 11)
        view.textColor = NSColor.init(hexColor: "#989A9D")
        view.backgroundColor = .clear
        return view
    }()
    
    private lazy var sendButton: TTButton = {
        let view = TTButton()
        view.tt_enabled = false
        view.tt_setImage(NSImage(named: "liveChatSendNormal"), for: .normal)
        view.tt_setImage(NSImage(named: "liveChatSendHover"), for: .hover)
        view.tt_setImage(NSImage(named: "liveChatSendPressed"), for: .press)
        view.tt_setImage(NSImage(named: "liveChatSendDisabled"), for: .disabled)
        view.tt_addTarget(self, action: #selector(didTapSendMessage), for: .leftMouseUp)
        return view
    }()
    
    private lazy var onlyTeacherCheckBox: TTButton = {
        let view = TTButton()
        view.tt_spacing = 6
        view.tt_enabledHover = false
        view.tt_titleAlignment = .right
        view.tt_titleFont = NSFont.systemFont(ofSize: 9)
        view.tt_setTitle("只看老师", for: .normal)
        view.tt_setTitleColor(NSColor.init(hexColor: "#808080"), for: .normal)
        view.tt_setImage(NSImage(named: "liveChatCheckboxNormal"), for: .normal)
        view.tt_setImage(NSImage(named: "liveChatCheckboxSelected"), for: .selected)
        view.tt_addTarget(self, action: #selector(self.didTapOnlyTeacher), for: .leftMouseUp)
        return view
    }()
    
    private lazy var clearButton: TTButton = {
        let view = TTButton()
        view.tt_titleFont = NSFont.systemFont(ofSize: 9)
        view.tt_setTitle("清空聊天", for: .normal)
        view.tt_setTitleColor(NSColor.init(hexColor: "#808080"), for: .normal)
        view.tt_addTarget(self, action: #selector(self.didTapClear), for: .leftMouseUp)
        return view
    }()
    
    private lazy var chatScrollView: NSScrollView = {
        let view = NSScrollView()
        view.scrollerStyle = .overlay
        view.scrollerKnobStyle = .dark
        view.verticalScrollElasticity = .automatic
        view.hasVerticalScroller = true
        view.documentView = chatsTableView
        view.backgroundColor = NSColor.init(hexColor: "#E9EEF2")
        return view
    }()
    
    private let lIdentifier = NSUserInterfaceItemIdentifier(TTChatLocalCell.className())
    private let rIdentifier = NSUserInterfaceItemIdentifier(TTChatRemoteCell.className())
    
    private let rowViewIdentifier = NSUserInterfaceItemIdentifier(NSTableRowView.className())
    
    private lazy var chatsTableView: NSTableView = {
        let view = NSTableView()
        view.headerView?.isHidden = true
        view.headerView = nil
        view.columnAutoresizingStyle = .noColumnAutoresizing
        view.delegate = self
        view.dataSource = self
        view.selectionHighlightStyle = .none
        view.intercellSpacing = NSSize(width: 0, height: 15)
       
        let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "Chat"))
        // 设置最小的宽度
        column.width = 240
        column.resizingMask = .autoresizingMask
        
        view.addTableColumn(column)
        
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
        setupMakeUI()

        setupMakeAddNotification()
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        
        textView.frame = textScrollView.bounds
    }
    
    deinit {
        print(#function + className)
    }
}

// MARK: - Private
extension TTLiveChatViewController {
    private func sendChatMessage(_ text: String) {
        let msg = TTMessage()
        msg.text = text
        
        let chatMessage = TTChatMessage()
        chatMessage.message = msg
        chatMessage.role = .local
        chatMessage.type = .message
        chatMessage.nickname = "陶建"
        
        print("发送信息")
        
        textView.stringValue = ""
        addChatMessage(chatMessage)
    }
    
    private func sendChatEmoticon(_ emoticon: TTEmoticon) {
        let chatMessage = TTChatMessage()
        chatMessage.emoticon = emoticon
        chatMessage.role = .local
        chatMessage.type = .emoji
        chatMessage.nickname = "陶建"
        
        print("发送信息")
        
        addChatMessage(chatMessage)
    }
}

// MARK: - Public
extension TTLiveChatViewController {
    public func addChatMessage(_ message: TTChatMessage) {
        if allMessage == nil {
            allMessage = []
            teacherMessages = []
        }
        
        allMessage?.append(message)
        if message.isTeacher {
            teacherMessages?.append(message)
        }
        
        messages = allMessage
    }
}

// MARK: - 点击事件
extension TTLiveChatViewController {
    
    @objc private func didTapOnlyTeacher(sender: TTButton) {
        sender.tt_selected = !sender.tt_selected
        
        if sender.tt_selected {
            messages = teacherMessages
            return
        }
        
        messages = allMessage
    }
    
    @objc private func didTapClear() {
        allMessage = nil
        teacherMessages = nil
        messages = nil
    }
    
    @objc private func didTapSendMessage() {
        let text = textView.stringValue
        sendChatMessage(text)
    }
    
    @objc private func textDidChange(notification: NSNotification) {
        
        guard let textField = notification.object as? NSTextField,
              textField == textView else { return }
        
        let text = textField.stringValue
        sendButton.tt_enabled = text.tt_trim.count > 0
    }
}

extension TTLiveChatViewController: NSTextFieldDelegate {
    
    func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        guard commandSelector == #selector(insertNewline(_:)) else { return false }
        let flags: NSEvent.ModifierFlags = [.shift]
        let modifierFlags = NSApplication.shared.currentEvent?.modifierFlags
        let isShift = modifierFlags?.contains(flags) ?? false
        if isShift {
            textView.insertNewlineIgnoringFieldEditor(self)
            return true
        }
        
        guard control.stringValue.count > 0 else { return false }
        
        sendChatMessage(control.stringValue)
        return true
    }
}

extension TTLiveChatViewController: TTEmoticonViewDelegate {
    func emojiViewDidTapSelected(data : TTEmoticon?) {
        guard let emoticon = data else { return }
        
        sendChatEmoticon(emoticon)
    }
}

extension TTLiveChatViewController: NSTableViewDataSource {
    
    func numberOfRows(in tableView: NSTableView) -> Int {
        let count = messages?.count ?? 0
        return count
    }
    
    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
        return messages?[row]
    }
    
    func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        
        var cell: TTChatCell? = nil
        guard let message = messages?[row] else { return cell }
        
        if message.role == .local {
            cell = tableView.makeView(withIdentifier: lIdentifier, owner: TTChatLocalCell.classForCoder()) as? TTChatLocalCell
            if cell == nil {
                cell = TTChatLocalCell()
                cell?.identifier = lIdentifier
            }
        }
        
        if message.role == .remote {
            cell = tableView.makeView(withIdentifier: rIdentifier, owner: TTChatRemoteCell.classForCoder()) as? TTChatRemoteCell
            if cell == nil {
                cell = TTChatRemoteCell()
                cell?.identifier = rIdentifier
                cell?.translatesAutoresizingMaskIntoConstraints = false
                cell?.autoresizingMask = .none
            }
        }
        cell?.chatMessage = message
        
        return cell
    }
    
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        return nil
    }
}

extension TTLiveChatViewController: NSTableViewDelegate {
    
    func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
        guard let chat = messages?[row] else { return 0 }
        
        var rowHeight: CGFloat = 50
        if chat.type == .message {
            let textHeight = chat.message?.textHeight ?? 0
            rowHeight = 17 + 10 + textHeight + 10
        }
        return rowHeight
    }
}

// MARK: - setup
extension TTLiveChatViewController {
    
    private func setupMakeAddNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(notification:)), name: NSControl.textDidChangeNotification, object: nil)
    }
    
    private func setupMakeAddSubviews() {
        
        view.addSubview(inputView)
        view.addSubview(onlyTeacherCheckBox)
        view.addSubview(clearButton)
        view.addSubview(chatScrollView)
        
        inputView.addSubview(emojiView)
        inputView.addSubview(handButton)
        inputView.addSubview(separatorView)
        inputView.addSubview(textScrollView)
        inputView.addSubview(sendButton)
    }
    
    private func setupMakeLayoutSubviews() {
        
        inputView.snp.makeConstraints { (make) in
            make.left.equalTo(4)
            make.bottom.right.equalTo(-4)
            make.height.equalTo(90)
        }
        
        onlyTeacherCheckBox.snp.makeConstraints { (make) in
            make.width.equalTo(55)
            make.height.equalTo(10)
            make.left.equalTo(4)
            make.bottom.equalTo(inputView.snp.top).offset(-5)
        }
        
        clearButton.snp.remakeConstraints { (make) in
            make.width.equalTo(40)
            make.height.equalTo(10)
            make.right.equalTo(-5)
            make.centerY.equalTo(onlyTeacherCheckBox)
        }
        
        chatScrollView.snp.remakeConstraints { (make) in
            make.top.equalTo(5)
            make.right.left.equalTo(view)
            make.bottom.equalTo(onlyTeacherCheckBox.snp.top).offset(-5)
        }
        
        // 输入view
        handButton.snp.remakeConstraints { (make) in
            make.right.top.equalTo(inputView)
            make.width.equalTo(40)
            make.height.equalTo(inputView).multipliedBy(0.5)
        }
        
        separatorView.snp.remakeConstraints { (make) in
            make.centerY.left.equalTo(handButton)
            make.height.equalTo(20)
            make.width.equalTo(2)
        }
        
        emojiView.snp.remakeConstraints { (make) in
            make.left.top.equalTo(inputView)
            make.right.equalTo(handButton.snp.left)
            make.height.equalTo(inputView).multipliedBy(0.5)
        }
        
        sendButton.snp.remakeConstraints { (make) in
            make.right.equalTo(inputView)
            make.top.equalTo(emojiView.snp.bottom).offset(2.5)
            make.height.equalTo(40)
            make.width.equalTo(40)
        }
        
        textScrollView.snp.remakeConstraints { (make) in
            make.left.equalTo(10)
            make.height.equalTo(28)
            make.right.equalTo(sendButton.snp.left)
            make.centerY.equalTo(sendButton)
        }
    }
    
    private func setupMakeUI() {
        view.tt_backgroundColor = .white
        
        var color:NSColor!
        color = NSColor.random()
        chatsTableView.tt_backgroundColor = color
        
        let emoticons = TTEmoticonSource(source: "Emoticons", ext: "bundle").path(resource: "Emoticons.plist", ofType: nil) ?? []
        if emoticons.count < 5 { return }
        
        var chatMessages = [TTChatMessage]()
        teacherMessages = []
        var msgCount = 50
        msgCount = Int(arc4random_uniform(300))
        msgCount = 0
        for i in 0..<msgCount {
            let chatMessage = TTChatMessage()
            chatMessages.append(chatMessage)
            
            chatMessage.isTeacher = (arc4random_uniform(2) % 2) == 1
            
            let type = TTChatType(rawValue:Int(arc4random_uniform(2))) ?? .message
            let role = TTChatRole(rawValue:Int(arc4random_uniform(2))) ?? .local
            chatMessage.type = type
            chatMessage.role = role
            chatMessage.nickname = "大傻逼"
            if role == .remote  {
                chatMessage.nickname = "远端大傻逼"
            }
            if chatMessage.isTeacher {
                chatMessage.nickname = "老师大傻逼"
                teacherMessages?.append(chatMessage)
                chatMessage.role = .remote
            }
            
            if type == .emoji {
                let emoticon = emoticons[i%5]
                chatMessage.emoticon = emoticon
                continue
            }
            let message = TTMessage()
            let str = "风扇电机浩丰科技阿技阿技阿"
            let str2 = "萨风扇电机浩丰\n科"
            let str3 = "技阿萨风\n扇电机浩丰科技"
            let str4 = "阿萨风扇电机浩丰科技阿萨德九分\n"
            let str5 = "风扇电机浩丰科技阿"
            let length = arc4random_uniform(5)
            var text = str
            if length > 1 { text += str2}
            if length > 2 { text += str3}
            if length > 3 { text += str4}
            if length > 4 { text += str5}
            message.text = text
            
            chatMessage.message = message
        }
        allMessage = chatMessages
        messages = allMessage
    }
}
